package kr.pe.xissy.soulmate.controller;

import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpSession;

import kr.pe.xissy.soulmate.domain.Note;
import kr.pe.xissy.soulmate.domain.User;
import kr.pe.xissy.soulmate.service.NoteService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping(value = {"/{email}/note"})
public class NoteController {

	@Autowired
	protected NoteService noteService;

	@RequestMapping(value = "", method = RequestMethod.GET)
	public String notes(Locale locale, Model model, HttpSession session, @PathVariable("email") String email) {
		boolean containsPrivate = false;
		if (SecurityContextHolder.getContext().getAuthentication().getName().equals(email)) {
			containsPrivate = true;
		}

		model.addAttribute("notes", noteService.findAllByEmail(email, containsPrivate));
		return "note";
	}

	@RequestMapping(value = "/today", method = RequestMethod.GET)
	public String todayNotes(Locale locale, Model model, HttpSession session, @PathVariable("email") String email) {
		boolean containsPrivate = false;
		if (SecurityContextHolder.getContext().getAuthentication().getName().equals(email)) {
			containsPrivate = true;
		}

		model.addAttribute("notes", noteService.findAllByEmailAndToday(email, containsPrivate));
		return "note";
	}

	@RequestMapping(value = "/write", method = RequestMethod.POST)
	@Secured("ROLE_USER")
	public String writeNote(Locale locale, Model model, HttpSession session, @RequestParam boolean isPrivate, @RequestParam String text) {
		User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

		Note note = new Note(isPrivate, new Date(), text);
		noteService.save(user, note);

		model.addAttribute(noteService.findAllByUserAndToday(user, false));

		return "note";
	}
}
